<?php
namespace App\Http\Controllers;
use App\Cafe_user;
use App\Cafe;
use App\City;
use App\Photo;
use App\Barista;
use App\Partner;
use App\Cafes_tags;
use App\Cafes_supplys;
use App\Dicts;
use App\Sale_order;
use App\Share;
use App\SysCafeLog;
use App\Tags;
use App\Sales;
use App\Goods;
use App\Assets;
use App\Beans;
use App\Supplys;
use App\UserPartner;
use App\Users;
use App\User_tags;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis as Redis;
use Illuminate\Support\Facades\DB;
use WeixinPay;

class API2Controller extends Controller
{
    /*
     * 创建咖啡馆
     */
    public function testq(){
        return respose()->json("aaaa");
    }
    public function  Impl_imageShare(Request $request){
        $headUrl=$request->headUrl;
        $title=$request->title;
        $body=$request->body;
        $path=$request->path;
        $logo=$request->logo  ?: "";


        $headPath=downPicGet($headUrl);
        $headUrl=uploadPic($headPath);
        $headUrl=$headUrl."?imageMogr2/crop/120x120";
        $headPath=downPicGet($headUrl);
        $imgg = yuan_img($headPath);
        imagepng($imgg,$headPath);
        imagedestroy($imgg);
        //传入path
       //$path="pages/front/cafe/detail/detail?id=1030";

        $qrcodeUrl=createQrcode($path,$logo);
        $qrcodePath=downPicGet($qrcodeUrl);
        $qrcodeUrl=uploadPic($qrcodePath);
        $qrcodeUrl=$qrcodeUrl."?imageMogr2/crop/211x240";
        $qrcodePath=downPicGet($qrcodeUrl);
        $imgBottom = ImageCreateFromPNG("bottom.png");
        $imgHead = ImageCreateFromPNG($headPath);
        $imgQrcode = imagecreatefromjpeg($qrcodePath);
        imagecopy($imgBottom, $imgHead, 147, 60, 0, 0, 120, 120);
        imagecopy($imgBottom, $imgQrcode, 102, 410, 0, 0, 211, 240);
        $fileName=date('Y-m-d-H-i-s') . '-' . uniqid().".jpg";
        // 为一幅图像分配颜色
        $cor = imagecolorallocate($imgBottom, 255, 255, 255);
        // 我们可以自定义与图片结合的文字字体
        $font = "./msyh.ttf";
      //  $body="  我在理想书店咖啡馆和十八个小伙伴一起杯测了七只豆子!";
        $info="识别二维码查看更多信息！";
        // 利用imagettftext()函数将文本“写入”图像
        imagettftext($imgBottom, 21, 0, 145, 250, $cor, $font, $title);
        for ($i = 0; $i < mb_strlen($body); $i++) {
            $line = floor($i / 17);
            $x = 25 + 22 * ($i - 17 * $line);
            imagettftext($imgBottom, 16, 0, $x, 300 + 30 * $line, $cor, $font, mb_substr($body, $i, 1));
        }
        for ($i = 0; $i < mb_strlen($info); $i++) {
            $line = floor($i / 17);
            $x = 80 + 22 * ($i - 17 * $line);
            imagettftext($imgBottom, 16, 0, $x, 720 + 30 * $line, $cor, $font, mb_substr($info, $i, 1));
        }

        imagejpeg($imgBottom,"$fileName",100);
        imagedestroy($imgBottom);
        $fileName= uploadPic($fileName);
        return response()->json($fileName);

    }
    public function Impl_unifiedOrder(Request $request)
    {
        $loginSession=$request->input('loginSession');
        $open_id=Redis::get($loginSession);
        $user = Users::where('wx_app_openid',$open_id)->first();

        $sale_id=$request->input('sale_id');
        $address_id=$request->input('address_id');
        $sale = Sales::find($sale_id);
        $goods = Goods::find($sale->goods_id);


        $supply = Supplys::find($sale->supply_id);
        $out_trade_no=$sale->sale_no.time().$user->id;
        $cover=$request->input('cardCover');
        $greetingWords=$request->input('greetingWords');

        
        if($user->partner_id)
        {
            $partner=Partner::find($user->partner_id);
            $key = $partner->app_key;
            $appid = $partner->appid;
            $mch_id = $partner->mch_id;
            
        }
        else
        {
            $key = 'Y2017Ccai4sfsaljLAsiANHL9D076HJE';
            $appid = 'wxb980d6dc4b2c0314';
            $mch_id = '1453239002';
        }



        if(empty($sale->body))
            $sale->body=" ";
        $saleOrder = new WeixinPay($open_id,$out_trade_no, $sale->price, $sale->body, $key, $appid, $mch_id);
        $pay = $saleOrder->pay();
        $saleOrderArrary=['out_trade_no'=>$out_trade_no,'sale_id'=>$sale_id,'goods_id'=>$sale->goods_id,'partner_id'=>$goods->partner_id,'address_id'=>$address_id,'user_id'=>$user->id,'order_price'=>$sale->price, 'cover'=>$cover, 'greetingWords'=>$greetingWords];

        Sale_order::create($saleOrderArrary);
        return response()->json($pay);
    }
    public function Impl_successOrder(Request $request){        //支付成功，更新资产表assets

        $loginSession=$request->input('loginSession');
        $open_id=Redis::get($loginSession);
        $user_id= Users::where('wx_app_openid',$open_id)->first()->id;

        $saleOrder = Sale_order::where('status', 0)
            ->where('user_id', $user_id)
            ->first();
        $saleOrder->status=1;
        $saleOrder->save();


        if($saleOrder->sale_id>0)   // 发货提醒
        {
            $sale = Sales::find($saleOrder->sale_id);
            if($sale->goods_id>0)
            {
                $goods = Goods::find($sale->goods_id);
                if($goods->partner_id)
                {
                    $users=UserPartner::where('partner_id',$goods->partner_id)->get();
                    var_dump($users);
                    foreach ($users as $user){
                        $phone=$user->user->phone;
                        $content="您有新的订单需要发货";
                        sendSms($phone,$content);
                    }
                }
            }


        }

        $this->updateAssets($saleOrder);   //更新资产表   
    }

    public function Impl_cancelOrder(Request $request){
        $loginSession=$request->input('loginSession');
        $open_id=Redis::get($loginSession);
        $user_id= Users::where('wx_app_openid',$open_id)->first()->id;
        Sale_order::where('status', 0)
            ->where('user_id', $user_id)
            ->update(['status' => 9]);
    }

    private function updateAssets($saleOrder)       //更新资产表，订单
    {
        $assets=new assets;
        $assets->count=1;
        $assets->price=$saleOrder->order_price;
        $assets->cover=$saleOrder->cover;
        $assets->user_id=$saleOrder->user_id;
        $sale = Sales::find($saleOrder->sale_id);
        $assets->supply_id=$sale->supply_id;
        $assets->save();
    }

    public function Impl_setQRCode(Request $request){
            $path=$request->input('path');
            $access_token_url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxb980d6dc4b2c0314&secret=4e1e32a82b0e24c7570e1555f1d71fe6";
            $res = json_decode($this->httpGet($access_token_url));
            $erweima="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$res->access_token";
            $data = array("path" => $path);
            $data_string = json_encode($data);
            $ch = curl_init($erweima);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json',
                    'Content-Length: ' . strlen($data_string))
            );
            $result = curl_exec($ch);
            file_put_contents("/data/wwwroot/yiicca/public/uploads/erweima.jpg", $result);
            return response()->download("/data/wwwroot/yiicca/public/uploads/erweima.jpg");
    }
    public function Impl_sysCafeLog(Request $request){
        $loginSession=$request->input('loginSession');
        $wx_app_openid=Redis::get($loginSession);

        if($wx_app_openid)
            $user_id= Users::where('wx_app_openid',$wx_app_openid)->first()->id;
        else
            $user_id='';

        $cafe_id=$request->cafe_id;
        $time=date("Y-m-d H:i:s",time());
        $syscafelog=new SysCafeLog;
        $syscafelog->user_id=$user_id;
        $syscafelog->cafe_id=$cafe_id;
        $syscafelog->time=$time;
        $syscafelog->save();
    }
    public function Impl_beanCreate(Request $request){
        $name=$request->input('name');

        $cafe=$request->input('cafe_id');
        $dict=$request->input('dict')+1;
        $tag=$request->input('tag')+1;
        $bean=new Beans;
        $bean->name=$name;
        $bean->dict_id=$this->getDictValue("continent",$dict);
        $bean->tag_id=$this->getTagID($bean->dict_id,$tag);
        $bean->cafe_id=$cafe;
        $bean->save();
        return response()->json($bean);
    }
    public  function  Impl_cafeCreate(Request $request){
        $name=$request->input('name');
        $letter=$this->getinitial($name);
        $address=$request->input('address');
        $latlng=$request->input('latlng');
        $loginSession=$request->input('loginSession');
        $wx_app_openid=Redis::get($loginSession);
        //    创建咖啡馆
        $cafe=new Cafe;
        $cafe->letter=$letter;
        $cafe->name=$name;
        $cafe->address=$address;
        $cafe->latlng=$latlng;
        $cafe->save();
        //获取access_token
        $access_token=$this->getAccessToken();
        //upload_qrcode（） help.php辅助函数。
        $path="pages/front/cafe/detail/detail?id=$cafe->id";
         $qrcode=createQrcode($path);
         $cafe->qrcode=$qrcode;
         $cafe->save();


//
       $addressComponent=publicGetAddr($latlng);
       $cafe->country = $addressComponent->country ?: "";
       $cafe->province = $addressComponent->province ?: "";
       $cafe->district = $addressComponent->district ?: "";
       $cafe->city = $addressComponent->city ?: $addressComponent->province;
       $cafe->citycode = $addressComponent->citycode ?: "";
       $cafe->adcode = $addressComponent->adcode ?: "";
       $cafe->street = $addressComponent->streetNumber->street ?: "";

       if($cafe->save()){
//发送短信
           $citycode=$this->getCitycodeByGps($latlng);
           $city=City::where('code',$citycode)->first();
           $cityuser=$city->user_city()->first();
           if(!empty($cityuser)){
               $phone=User::find($cityuser->user_id)->phone;
               $phone="$phone,15898965731,15275562660";
           }else{
               $phone="15898965731,15275562660";
           }
           $text="有".$city->name."的咖啡馆加入平台，请到公众号中审核";
           // publicSendSms($phone,$text);
           $cafe_id=$cafe->id;
           $cafe_user=new Cafe_user;
           $user=Users::where('wx_app_openid',$wx_app_openid)->first();
           $user_id= $user->id;
           $cafe_user->user_id=$user_id;
           $cafe_user->cafe_id=$cafe_id;
           $cafe_user->save();
           $mobile=$user->phone;
           if(!empty($mobile)){
               $text="您的咖啡馆添加成功，请完善信息，我们将尽快审核上线";
               // publicSendSms($mobile,$text);
           }
          ;
       }
       return response()->json($cafe);
    }
    /*
     * 完善咖啡馆信息
     */
    public  function  Impl_cafeComplete(Request $request){
        $loginSession=$request->input('loginSession');
        $name=$request->input('name');
        $open_time=$request->input('open_time');
        $close_time=$request->input('close_time');
        $week=$request->input('week');
        $phone=$request->input('phone');
        $wifi=$request->input('wifi');
        $weibo=$request->input('weibo');
        $summary=$request->input('summary');
        $tag=$request->input('tag');
        $address=$request->input('address');
        $latlng=$request->input('latlng');
        $bus=$request->input('bus');
        $tag_array = explode(',',$tag);
        $wx_app_openid=Redis::get($loginSession);
        $user=new Users;
        $user->wx_app_openid=$wx_app_openid;
        $user->name=$name;
        $findUser = $this->findUser($user);
        if(!empty($findUser))   //找到更新
        {
            $cafe= Users::find($findUser->id)->cafes->first();
            foreach($tag_array as $item){
                $cafe_tag=new Cafes_tags;
                $cafe_tag->cafe_id=$cafe->id;
                $cafe_tag->tag_id=$item;
                $cafe_tag->save();
            }
            $cafes=Cafe::find($cafe->id);
            $cafes->name=$name;
            $cafes->open_time=$open_time;
            $cafes->close_time=$close_time;
            $cafes->week=$week;
            $cafes->phone=$phone;
            $cafes->wifi=$wifi;
            $cafes->weibo=$weibo;
            $cafes->address=$address;
            $cafes->latlng=$latlng;
            $cafes->bus=$bus;
            $cafes->summary=$summary;

            $cafes->save();
        }
        return response()->json($findUser);
    }
    //根据3rd_session得到客户端登录用户
    public function Impl_userRegister(Request $request)
    {
        $user = new Users;
        $user->nickname = $request->input('nickName');
        $user->headimgurl = $request["avatarUrl"];
        $user->city = $request["city"];
        $user->country = $request["country"];
        $user->sex = $request["gender"];
        $user->language = $request["language"];
        $user->partner_id = $request["partner_id"];
        $user->province = $request["province"];
        $user->wx_app_openid = Redis::get($request->input('loginSession'));         //至此拿到需要注册的完整用户信息
        return response()->json($this->userRegister($user));
    }
    //根据3rd_session得到客户端登录用户
    public function Impl_userPhoneRegisterStatus(Request $request)
    {
        $user = new Users;
        $user->wx_app_openid = Redis::get($request->input('loginSession'));         
        $findUser = $this->findUser($user);
        return response()->json($findUser->phone);
    }
    

    /*
     * app上传照片接口
     */
    public function Impl_photoCreate(Request $request){
        $cafe_id=$request->input('cafe_id');
        $img=$request->file('img');
        $body=$request->input('body');
        $url = upload_one($img);
        $photo=new Photo;
        $photo->url=$url;
        if(str_contains($url, "http://onecafe")){
            $url=$url."?imageInfo";
            $rs=dealHttp($url);
            $width=$rs->width;
            $height=$rs->height;
            $photo->width=$width;
            $photo->height=$height;
        }
        $photo->body=$body;
        $photo->cafe_id=$cafe_id;
        $photo->save();
        return response()->json($photo);

    }

    //修改为私有方法，建议使用
    private function userRegister($user)
    {
        $findUser = $this->findUser($user);
        if(!empty($findUser))   //找到更新
        {
            $findUser->wx_app_openid = $user->wx_app_openid;
            $findUser->partner_id = $user->partner_id;
            $findUser->save();
            // return "更新了用户";
            $findUser->info="更新了用户";
            return response()->json($this->getUserWithRole($findUser));
        }
        else
        {
            $newUser = new Users;
            $newUser = $user;
            $newUser->save();
            $newUser->info="新增了用户";
            return response()->json($newUser);
            // return "新增了用户";
        }
        return "注册失败";
    }
    private function getUserWithRole($user)
    {
        //附加用户的权限列表，1.如果有管理的咖啡馆，添加咖啡馆主理人权限。2.如果有烘焙师信息，添加烘焙师角色
        $roles = $user->roles;

        $cafes=$user->cafes;
        if($user->beanBaker)
        {
            $role = Tags::find(981);        //981咖啡烘焙师角色
            $roles->push($role);
        }
        if(sizeof($cafes)>0)
        {
            $role = Tags::find(984);        //984咖啡馆主理人角色
            $roles->push($role);
        }
         if($user->user_citys)
         {
             $role = Tags::find(988);        //988城市联系人角色
             $roles->push($role);
         }
        $user->roles = $roles;

        $userMenus=collect();
        foreach ($roles as $role) {
            $collection = $role->menus;
            $userMenus = $collection->merge($userMenus);
        }

        $user->menus = $userMenus;
        return $user;

    }
    private function findUser($user)
    {
        if($user->wx_app_openid)        //排除wx_app_openid空的情况
        {
            $findUser = Users::where('wx_app_openid', $user->wx_app_openid)->first();
            if(!empty($findUser))
                return $findUser;
        } 
        

        return $findUser;
    }
    /*
     * cafeupdate页面的数据
     */
    public function Impl_cafeUpdate(Request $request){
        $cafeTags = explode(',', $request->input('tagsStr'));

        $latlng=$request->input('latlng');
        $address=$request->input('address');
        $logo=$request->input('logo');
        $logo = substr($logo, 0, 26) . "pictj" . substr($logo, 31);
        
        $slogan=$request->input('slogan');
        $since_year=$request->input('since_year');
        $bus=$request->input('bus');
        $id=$request->input('id');
        $name=$request->input('name');
        $open_time=$request->input('open_time');
        $close_time=$request->input('close_time');
        $weekend_open_time=$request->input('weekend_open_time');
        $weekend_close_time=$request->input('weekend_close_time');

        $week=$this->getTagID(6,$request->input('week')+1); //得到处理方式tagid
        $weekend=$this->getTagID(21,$request->input('weekend')+1); //得到处理方式tagid

        $phone=$request->input('phone');
        $summary=$request->input('summary');
        $cafe=Cafe::find($id);
        $cafe->address=$address;
        $cafe->latlng=$latlng;
        $cafe->logo=$logo;

        $bool = str_contains($logo, 'pictj');
        if($bool){
            $path="pages/front/cafe/detail/detail?id=$cafe->id";
            $qrcode=createQrcode($path,$logo);
            $cafe->qrcode=$qrcode;
        }

        // $cafe->slogan=$slogan;
        $cafe->since_year=$since_year;
        $cafe->bus=$bus;
        $cafe->name=$name;
        $cafe->letter=$this->getinitial($name);

        $cafe->open_time=$open_time;
        $cafe->close_time=$close_time;
        $cafe->week=$week;
        $cafe->weekend=$weekend;
        $cafe->weekend_open_time=$weekend_open_time;
        $cafe->weekend_close_time=$weekend_close_time;

        $cafe->phone=$phone;
        $cafe->summary=$summary;

        $addressComponent=publicGetAddr($latlng);
        $cafe->country = $addressComponent->country ?: "";
        $cafe->province = $addressComponent->province ?: "";
        $cafe->district = $addressComponent->district ?: "";
        $cafe->city = $addressComponent->city ?: $addressComponent->province;
        $cafe->citycode = $addressComponent->citycode ?: "";
        $cafe->adcode = $addressComponent->adcode ?: "";
        $cafe->street = $addressComponent->streetNumber->street ?: "";

        if($cafe->save()){
            $tagArr=$this->getTagsByDict(3);
            Cafes_tags::where('cafe_id',$cafe->id)
                ->wherein('tag_id',$tagArr)
                ->delete();
            foreach($cafeTags as $item){
                $cafe_tag= new Cafes_tags;
                $cafe_tag->cafe_id=$cafe->id;
                $cafe_tag->tag_id=$item;
                $cafe_tag->save();
            }
        }
        return response()->json($cafe);
    }
    public function Impl_nearbyBus(Request $request)
    {
        $latlng = $request->input('latlng');
        $nearby = file_get_contents('http://restapi.amap.com/v3/place/around?key=291f9ad46a4ab46cc442157ca8b573c8&location='.$latlng.'&output=JSON&radius=500&keywords=公交车');

        $nearby = json_decode(($nearby));
        $pois = $nearby->pois;         //逆地理编码列表
        return response()->json($pois);
    }
    public function Impl_nearbyMetro(Request $request)
    {
        $latlng = $request->input('latlng');
        $nearby = file_get_contents('http://restapi.amap.com/v3/place/around?key=291f9ad46a4ab46cc442157ca8b573c8&location='.$latlng.'&output=JSON&radius=1000&keywords=地铁');

        $nearby = json_decode(($nearby));
        $pois = $nearby->pois;         //逆地理编码列表
        return response()->json($pois);
    }

    public function Impl_cafeStatus(Request $request){
        $id = $request->input('id');
        $status=$request->input('status');

        $cafe=Cafe::find($id);
        if($status==true)
            $cafe->status=1;
        else
            $cafe->status=0;

        $cafe->save();
        return response()->json($cafe);
    }
    /*
     *
     */
    public function Impl_updateDesignSummary(Request $request){
        $id=$request->input('id');
        $design_summary=$request->input('design_summary');
        $cafe=Cafe::find($id);
        $cafe->design_summary=$design_summary;
        $cafe->save();
    }
    public function Impl_roleUpdate(Request $request){
        $loginSession=$request->loginSession;
        $from=$request->fromSession;
        $from_user=$this->getUserByAppUserSession($from);
        $to_user=$this->getUserByAppUserSession($loginSession);
//        $userTag=new User_tags();
//        $userTag->from_user_id=$from_user->id;
//        $userTag->user_id=$to_user->id;
//        $userTag->tag_id=$request->role;
//        $userTag->save();
    }



    public function Impl_cafeSupplyUpdate(Request $request){
        $supply=$request->input('supply_id');
        $this->cafeSupplyUpdate($request->input('cafe_id'),$supply);
    }
    public function Impl_recordShare(Request $request){
        //checkFirst
        $path=$request->path;
        $loginSession=$request->loginSession;
        $from=$request->from;
        $from_user=$this->getUserByAppUserSession($from);
        $to_user=$this->getUserByAppUserSession($loginSession);

        $count = Share::where('from_user_id', $from_user->id)->where('to_user_id', $to_user->id)->where('path', $path)->count();
        $share=new Share();

        if($count>0)      //已经分享，设置
        {   
            $share->status = 1;
            $share->fromUserName = $from_user->nickname;
            $share->fromUserHeadImg = $from_user->headimgurl;
        }
        else        //没有分享过，开始分享
        {
            $cafe_id=$request->cafe_id;
            $supply_id=$request->supply_id;
            $tag_id=$request->tag_id;
            $goods_id=$request->goods_id;
            $title=$request->title;
            


            $share->from_user_id=$from_user->id;
            $share->to_user_id=$to_user->id;
            $share->cafe_id=$cafe_id;
            $share->supply_id=$supply_id;
            $share->tag_id=$tag_id;
            $share->goods_id=$goods_id;
            $share->title=$title;
            $share->path=$path;
            
            if($from_user->id&&$to_user->id)  
            {
                if($share->save())     
                {
                    $assets = new Assets();
                    $assets->user_id = $to_user->id;
                    // $this->updateAssets($assets);
                    // if($request->type=="bean")      //to_user更新资产一个咖啡豆
                    // {
                        
                    // }
                }

            }      
            $share->fromUserName = $from_user->nickname;
            $share->fromUserHeadImg = $from_user->headimgurl;
        }

        
        return response()->json($share);
    }

    public function Impl_newBarista(Request $request){
        $loginSession=$request->loginSession;
        $fromSession=$request->fromSession;
        $formId = $request->formId;
        $role = $request->role;     //邀请的是什么角色？咖啡师、烘焙师？
        $user=$this->getUserByAppUserSession($loginSession);
        $shareUser=$this->getUserByAppUserSession($fromSession);

        $barista = Barista::where('user_id',$user->id)->where('role_id',$role)->first();
        if(empty($barista))
        {
            $toNewBaristaMsg = collect();
            $keyword1=['value' => $user->nickname, 'color' => '#000000'];
            $keyword2=['value' => '接受邀请', 'color' => '#000000'];
            $keyword3=['value' => '进入一间咖啡馆编辑烘焙师资料分享烘焙好豆', 'color' => '#000000'];
            $toNewBaristaMsg->put('keyword1', $keyword1);
            $toNewBaristaMsg->put('keyword2', $keyword2);
            $toNewBaristaMsg->put('keyword3', $keyword3);

            $barista=new Barista();
            $barista->user_id = $user->id;
            $barista->share_user_id = $shareUser->id;
            $barista->role_id = $role;
            if($barista->save())
            {
                $this->sendTemplateMsg($user->wx_app_openid, 'RAo9c39hmR5b-Rf4wVmIqKzA78UzrRcEDwEfcllx0x4', '/pages/CURD/barista/beanBaker/home/home', $formId, $toNewBaristaMsg);
            }
        }
       
        return $barista;

    }
    public function Impl_updateBarista(Request $request){
        $id=$request->input('id');
        $since_year=$request->input('since_year');
        $barista_name=$request->input('barista_name');
        $summary=$request->input('summary');

        $barista=Barista::find($id);
        $barista->barista_name=$barista_name;
        $barista->since_year=$since_year;
        $barista->summary=$summary;
        $barista->save();
        return $barista;

    }
    public function Impl_infoBarista(Request $request){
        $loginSession=$request->loginSession;
        $user=$this->getUserByAppUserSession($loginSession);

        $barista = Barista::where('user_id', $user->id)->first();
        return $barista;

    }
    public function Impl_detailBarista(Request $request){
        $id=$request->barista_id;

        $barista = Barista::find($id);
        $barista->info;
        return $barista;

    }
    public function Impl_listBarista(Request $request){
        $loginSession=$request->loginSession;
        $share_user=$this->getUserByAppUserSession($loginSession);
        $baristas = Barista::where("share_user_id",$share_user->id)->get();
        foreach ($baristas as $barista) {
            # code...
            $barista->info;
        }
        return $baristas;
    }

    public function Impl_cafeSupplyUpdates(Request $request){
        $supplys=$request->input('supplys');
        $supplys = explode(',', $supplys);
        $this->cafeSupplysUpdate($request->input('cafe_id'),7,$supplys);
    }



    public function Impl_pikerFromDicts(Request $request){
        $category=$request->input('category');
        $sort=$request->input('sort')+1;

        $picker = $this->getPickerDataFromDicts($category,$sort);
        return response()->json($picker);
    }
    public function Impl_pikerFromTags(Request $request){
        $dict=$request->input('dict');
        $barista=$request->input('barista');

        $picker = $this->getPickerDataFromTags($dict,0);
        return response()->json($picker);
    }

    //拿到某个category的第几个dict以及该dict对应的tags
    private  function  getPickerDataFromDicts($category,$sort){
        $picker=array();
        $dictsArr=array();
        $tagsArr=array();
        $dicts = DB::table('dicts')
                     ->where('category', $category)
                     ->orderBy('sort', 'asc')
                     ->get();
        
        $dictsArr['dicts']=$dicts;
        $dictsArr['index']=$sort-1;

        $dict = Dicts::where('sort',$sort)->where('category', $category)->first();
        $tagsArr=$this->getPickerDataFromTags($dict->id,0);

        $picker['main'] = $dictsArr;
        $picker['sub'] = $tagsArr;
        return $picker;
    }

    //更新咖啡馆的供应,单一和一组
    private function cafeSupplyUpdate($cafe,$supply)
    {
        //如果找到删除，否则插入
        $count = Cafes_supplys::where('cafe_id',$cafe)
                ->where('supply_id',$supply)
                ->count();
        if($count>0)
        {
            Cafes_supplys::where('cafe_id',$cafe)
                ->where('supply_id',$supply)
                ->delete();
        }
        else
        {
            $cafe_supply= new Cafes_supplys;
            $cafe_supply->cafe_id=$cafe;
            $cafe_supply->supply_id=$supply;
            $cafe_supply->save();
        }
    }
    private function cafeSupplysUpdate($cafe,$dict,$supplys)
    {
        $supplyArr=$this->getSupplysByDict($dict);
        Cafes_supplys::where('cafe_id',$cafe)
                ->wherein('supply_id',$supplyArr)
                ->delete();
        foreach($supplys as $item){
            $cafe_supply= new Cafes_supplys;
            $cafe_supply->cafe_id=$cafe;
            $cafe_supply->supply_id=$item;
            $cafe_supply->save();
        }
    }
    
    /*
     * 根据字典id
     * 将相应的tag添加到一个分组里
     */
    private function getTagsByDict($dict)
    {
        $tags = Tags::where('category', $dict)->get();
        $tagsArr=array();
        foreach ($tags as $tag) {
            array_push($tagsArr,$tag->id);
        }
        return $tagsArr;
    }
    private function getSupplysByDict($dict)
    {
        $supplys = Supplys::where('category', $dict)->get();
        $supplysArr=array();
        foreach ($supplys as $supply) {
            array_push($supplysArr,$supply->id);
        }
        return $supplysArr;
    }
/*
 * 咖啡馆细节
 */
    public function Impl_cafeDetail(Request $request){
        $cafe_id=$request->input('cafe_id');
        $cafe=Cafe::find($cafe_id);

        $supplys = $cafe->supplys;

        //拿到供应的意式咖啡，单品咖啡以及甜品的数据
        $publicCoffeeSupplys=Supplys::where('category',7)->where('public',1)->get();      
        $privateCoffeeSupplys=Supplys::where('category',7)->where('cafe',$cafe_id)->get(); 
        $publicCoffeeSupplys=$this->getCheckboxTags($supplys->where('category',7),$publicCoffeeSupplys);
        $privateCoffeeSupplys=$this->getCheckboxTags($supplys->where('category',7),$privateCoffeeSupplys);
        //增加图片数量
        $cafe->publicCoffeeSupplys = $this->getMoreSupplyInfo($publicCoffeeSupplys);
        $cafe->privateCoffeeSupplys = $this->getMoreSupplyInfo($privateCoffeeSupplys);

        $publicMagazineSupplys=Supplys::where('category',14)->where('public',1)->get();      
        $publicMagazineSupplys=$this->getCheckboxTags($supplys->where('category',14),$publicMagazineSupplys);
        //增加图片数量
        $cafe->publicMagazineSupplys = $this->getMoreSupplyInfo($publicMagazineSupplys);

        // $cafe->coffeeSupplys=$this->getCheckboxTags($supplys->where('category',7),$publicCoffeeSupplys->merge($privateCoffeeSupplys));

        $privateDanpinSupplys=Supplys::where('category',8)->where('cafe',$cafe_id)->get();  
        $privateDanpinSupplys=$this->getCheckboxTags($supplys->where('category',8),$privateDanpinSupplys);
        $cafe->privateDanpinSupplys = $this->getMoreSupplyInfo($privateDanpinSupplys);
        
        
        $privateDessertSupplys=Supplys::where('category',9)->where('cafe',$cafe_id)->get(); 
        $privateDessertSupplys=$this->getCheckboxTags($supplys->where('category',9),$privateDessertSupplys); 
        $cafe->privateDessertSupplys = $this->getMoreSupplyInfo($privateDessertSupplys);

        $cafe->cafeTags=$this->getCafeTags($cafe);
        $cafe->allTags=$this->getAllCafeTags($cafe->id);
        //到咖啡馆的time1，time2和week
        $cafe->week=$this->getPickerDataFromTagsByID(6,$cafe->week);
        $cafe->weekend=$this->getPickerDataFromTagsByID(21,$cafe->weekend);
        
        $photos=$cafe->photos()->get();
        if($photos->count()>9){
            $photos=$photos->sortBy('sort')->take(9);
        }else{
            $photos=$photos->sortBy('sort');
        }

        $thePhotos = collect();  
        $sort = 1;
        foreach ($photos as $photo) {
            $photo->sort = $sort;
            $photo->save();
            $sort++;
            $thePhotos->push($photo);
        }
        $photos = $thePhotos->sortBy("sort");
        $cafe->cafePhotos=$photos;

        return response()->json($cafe);
    }


    private function getCafeTags($cafe)
    {
        $tags = $cafe->tags->where('category',3);
        $tagsArr=array();
        foreach ($tags as $tag) {
            array_push($tagsArr,$tag);
        }
        return $tagsArr;

    }
    private function getAllCafeTags($cafe)
    {
        $cafeTags=Tags::where('category',3)->orderBy('sort', 'asc')->get();

        $publicTags=$cafeTags->where('public',1);      
        $cafeTags=$cafeTags->where('cafe',$cafe);      
        return $cafeTags->merge($publicTags);

    }

    private  function  getTagID($dict,$tag_index){
        if($tag_index)
            $value=Tags::where('category',$dict)->where('sort',$tag_index)->first()->id;
        else
            $value = 0;
        return $value;
    }
    private  function  getPickerDataFromTagsByID($dict,$tag_id){
        $tagsArr=array();
        $tags=Dicts::find($dict)->showtags()->orderBy('sort', 'asc')->get();
        if($tag_id)
            $index=Tags::where('id',$tag_id)->first()->sort-1;
        else
            $index = -1;
        
        $tagsArr['tags']=$tags;
        $tagsArr['index']=$index;
        return $tagsArr;
    }
    private function getPickerDataFromArr($arr,$id)
    {
        $pickerData = $arr->sortBy("sort");   //排序
        $index=0;
        $pickerIndex=0;
        foreach ($pickerData as $row) {
            $row->sort=$index;
            if($row->id==$id)
                $pickerIndex=$row->sort;
            $index++;
        }

        $pickerArr=array();
        foreach ($pickerData as $row) {
            array_push($pickerArr, $row);
        }

        $returnArr=array();             //包装数据返回
        $returnArr['pickerData']=$pickerArr;
        $returnArr['index']=$pickerIndex;
        return $returnArr;
    }
    private function getMoreSupplyInfo($supplys)
    {
        foreach ($supplys as $supply) {
            $photos = $supply->photos;
            $supply->flavours=$supply->tags;    
            $supply->photoCount=$photos->count();
        }
        return $supplys;
    }
    private  function  getCheckboxTags($checkTags,$allTags){
        foreach($allTags as $item){
            if(count($checkTags)==0){
                $item->checked=false;
            }else{
                foreach($checkTags as $p){
                    if($p->id==$item->id){
                        $item->checked=true;
                        break;
                    }else{
                        $item->checked=false;
                    }
                }
            }

        }
        return $allTags;
    }

    private function getAccessToken(){
        //首先判断token是否过期
        $access_token=Redis::get('access_token');
        if(empty($access_token)){
            $access_token_url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxb980d6dc4b2c0314&secret=4e1e32a82b0e24c7570e1555f1d71fe6";
            $res=dealHttp($access_token_url);
            $access_token=$res->access_token;
            //给token赋值，并设置token生存时间3600秒
            Redis::set('access_token',$access_token);
            Redis::expire('access_token',3600);

        }
        //更新token值
        $access_token=Redis::get('access_token');
        return $access_token;
    }
    public function Impl_detailUser(Request $request){
        $loginSession=$request->input('loginSession');
        $wx_app_openid=Redis::get($loginSession);

        //echo $loginSession;
        // echo "###".$wx_app_openid;
        $user=Users::where('wx_app_openid',$wx_app_openid)->select('id','nickname','headimgurl','phone')->first();
        $user->manageCafes=Users::find($user->id)->cafes()->get();
        foreach ($user->manageCafes as $cafe) {
            $cafe->photos;
        }

        if(!empty(Users::find($user->id)->user_citys()->first())){
            $user_citys=Users::find($user->id)->user_citys()->get();
            foreach ($user_citys as $item){
                $item->cityCafes=Cafe::where('citycode',$item->code)->get();
            }
            $user->manageCitys=$user_citys;

        }
        $likeCafes=Users::find($user->id)->likeCafes;
        $visitedCafes=Users::find($user->id)->visitedCafes;
        $assets=Users::find($user->id)->assets;


        $likeCafesArr = array();        //数据经过sortBy函数后变成了对象，不适合前端处理，重新封装到数组中
        $visitedCafesArr = array();        //数据经过sortBy函数后变成了对象，不适合前端处理，重新封装到数组中
        // 整理数据
        foreach ($likeCafes as $cafe) {
            $tags=$cafe->tags;
            $cafe->cafeTags=$tags->where('category',3);

            $photos = $cafe->photos()->get();
            $photos = $photos->sortBy('sort');
            if(empty($cafe->cover))
                $cafe->cover = $photos->first()->url;
            if($cafe->status)
                array_push($likeCafesArr,$cafe);
        }
        $user->likeCafes = $likeCafesArr;
        //整理足迹
        foreach ($visitedCafes as $cafe) {
            $tags=$cafe->tags;
            $cafe->cafeTags=$tags->where('category',3);

            $photos = $cafe->photos()->get();
            $photos = $photos->sortBy('sort');
            if(empty($cafe->cover))
                $cafe->cover = $photos->first()->url;
            if($cafe->status)
                array_push($visitedCafesArr,$cafe);
        }
        $user->visitedCafes = $visitedCafesArr;

        $user->assets = $assets;
        $user->partners;


        return response()->json($this->getUserWithRole($user));
    }
    //getPickerDataFromTags(dict,tag)
    //接收参数是字典的id和标签的id，
    //返回的是一个数组，数组内容包括两部分：
    //Impl_pikerFromTags

    private  function  getPickerDataFromTags($dict,$tag_value){
        $tagsArr=array();
        $tags=Dicts::find($dict)->showtags()->orderBy('sort', 'asc')->get();
        $tags = $tags->sortBy('sort');
        $index=Tags::where('value',$tag_value)->first()->sort;
        if(empty($index))
            $index=0;
        if($dict==13)
        {
            foreach ($tags as $tag) {
                $tag->name=$tag->name2.$tag->name;
            }
        }
        $tagsArr['tags']=$tags;
        $tagsArr['index']=$index;
        return $tagsArr;
    }
    
    private  function  getTagValue($dict,$tag_index){
        $value=Tags::where('category',$dict)->where('sort',$tag_index)->first()->value;
        return $value;
    }
    // private  function  getTagID($dict,$tag_index){
    //     $value=Tags::where('category',$dict)->where('sort',$tag_index)->first()->id;
    //     return $value;
    // }
    private  function  getDictValue($category,$sort){
        $dicts = DB::table('dicts')
                     ->where('category', $category)
                     ->where('sort', $sort)
                     ->get();
        $dict = $dicts[0];
        return $dict->id;
    }
    public function getinitial($s0)
    {
        $s0 = mb_substr($s0,0,1,'utf-8');
        $s=iconv('UTF-8//TRANSLIT//IGNORE','gb2312', $s0);
        if (ord($s0)>128) { //汉字开头
            $asc=ord($s{0})*256+ord($s{1})-65536;
            if($asc>=-20319 and $asc<=-20284)return "A";
            if($asc>=-20283 and $asc<=-19776)return "B";
            if($asc>=-19775 and $asc<=-19219)return "C";
            if($asc>=-19218 and $asc<=-18711)return "D";
            if($asc>=-18710 and $asc<=-18527)return "E";
            if($asc>=-18526 and $asc<=-18240)return "F";
            if($asc>=-18239 and $asc<=-17923)return "G";
            if($asc>=-17922 and $asc<=-17418)return "I";
            if($asc>=-17417 and $asc<=-16475)return "J";
            if($asc>=-16474 and $asc<=-16213)return "K";
            if($asc>=-16212 and $asc<=-15641)return "L";
            if($asc>=-15640 and $asc<=-15166)return "M";
            if($asc>=-15165 and $asc<=-14923)return "N";
            if($asc>=-14922 and $asc<=-14915)return "O";
            if($asc>=-14914 and $asc<=-14631)return "P";
            if($asc>=-14630 and $asc<=-14150)return "Q";
            if($asc>=-14149 and $asc<=-14091)return "R";
            if($asc>=-14090 and $asc<=-13319)return "S";
            if($asc>=-13318 and $asc<=-12839)return "T";
            if($asc>=-12838 and $asc<=-12557)return "W";
            if($asc>=-12556 and $asc<=-11848)return "X";
            if($asc>=-11847 and $asc<=-11056)return "Y";
            if($asc>=-11055 and $asc<=-10247)return "Z";
        }else if(ord($s)>=48 and ord($s)<=57){ //数字开头
            switch(iconv_substr($s,0,1,'utf-8'))
            {
                case 1:return "Y";
                case 2:return "E";
                case 3:return "S";
                case 4:return "S";
                case 5:return "W";
                case 6:return "L";
                case 7:return "Q";
                case 8:return "B";
                case 9:return "J";
                case 0:return "L";
            }
        }else if(ord($s)>=65 and ord($s)<=90){ //大写英文开头
            return substr($s,0,1);
        }else if(ord($s)>=97 and ord($s)<=122){ //小写英文开头
            return strtoupper(substr($s,0,1));
        }
        else
        {
            return iconv_substr($s0,0,1,'utf-8');//中英混合的词语，不适合上面的各种情况，因此直接提取首个字符即可
        }
    }
    private function getCitycodeByGps($latlng)
    {
        $homepage = file_get_contents('http://restapi.amap.com/v3/geocode/regeo?output=JSON&location='.$latlng.'&key=291f9ad46a4ab46cc442157ca8b573c8&radius=1000&extensions=all');
        $homepage = json_decode(($homepage));
        $regeocodes = $homepage->regeocode;//逆地理编码列表
        $addressComponent =  $regeocodes->addressComponent;
        return $addressComponent->citycode;
    }
    private function getUserByAppUserSession($loginSession){
        $wx_app_openid=Redis::get($loginSession);
        if($wx_app_openid)
        {
            $user = DB::table('users')->select("id","nickname","wx_app_openid","headimgurl")->where('wx_app_openid', $wx_app_openid)->first();
            return $user;
        }
        else
            return false;
        
    }
    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
        // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }
}
